package com.blacktea.behavioralpatterns.mementopattern.service;

import com.blacktea.behavioralpatterns.mementopattern.Cart;
import com.blacktea.behavioralpatterns.mementopattern.CartMemento;
import com.blacktea.behavioralpatterns.mementopattern.Goods;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Stack;

/**
 * @description: 购物车服务类
 * @author: black tea
 * @date: 2023/3/25 20:14
 */
@Service
@RequiredArgsConstructor
public class CartService {

    private final Cart cart;
    private final Stack<CartMemento> history = new Stack<>();

    /**
     * 添加商品
     * @param goods 商品对象
     */
    public void addGoods(Goods goods){
        history.push(cart.createMemento());
        cart.addItem(goods);
    }

    /**
     * 撤销操作
     */
    public void undo() {
        if (!history.isEmpty()) {
            CartMemento memento = history.pop();
            cart.restoreMemento(memento);
        }
    }

    public List<Goods> getGoodsList(){
        return cart.getItems();
    }

    public BigDecimal getTotalPrice(){
        return cart.getTotalPrice();
    }

}
